//
//  SEGNewSelectCommunityViewController.m
//  SEGUhomeStandard
//
//  Created by 揭婧雯 on 2018/8/14.
//  Copyright © 2018年 刘山. All rights reserved.
//

#import "SEGNewSelectCommunityViewController.h"

#import "SEGCommunitySearchView.h"
#import "SEGNoSearchCommunityResultView.h"
#import "SEGSelectCommunityHeaderView.h"
#import "SEGSelectCityView.h"
#import "SEGBigNavigationView.h"
#import "SEGNewSelectCommunityCell.h"

#if __has_include(<BMKLocationKit/BMKLocationManager.h>)
#import <BMKLocationKit/BMKLocationManager.h>
#else
#import "BMKLocationManager.h"
#endif
#if __has_include(<Commom/SEGLayoutMacro.h>)
#import <Commom/SEGLayoutMacro.h>
#else
#import "SEGLayoutMacro.h"
#endif
#import "CCLocationManager.h"

#import "SEGNewSelectCommunityViewModel.h"

const static CGFloat tagMargin = 10.0;

@interface SEGNewSelectCommunityViewController () <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, BMKLocationManagerDelegate, SEGNewSelectCommunityCellDelegate, SEGSelectCityViewDelegate>

/// 大标题导航栏
@property (nonatomic, strong) SEGBigNavigationView *bigNavView;
/// 头部搜索视图
@property (nonatomic, strong) SEGCommunitySearchView *searchView;
/// 头部搜索视图
@property (nonatomic, strong) SEGNoSearchCommunityResultView *noSearchResultView;
/// 列表
@property (nonatomic, strong) UITableView *tableView;
/// 选择城市视图
@property (nonatomic, strong) SEGSelectCityView *selectCityView;
/// 定位未授权弹窗
@property (nonatomic, strong) UIAlertView *alertView;
/// 热门小区标签
@property (nonatomic, strong) SEGTagList *tagList;

@property(nonatomic, strong) BMKLocationManager *locationManager;

/// viewModel
@property (nonatomic, strong) SEGNewSelectCommunityViewModel *viewModel;

@end

@implementation SEGNewSelectCommunityViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated {
    if (self.isFromLogin) { // 注册页面进入
        self.searchView.communityNameText.keyboardType = UIKeyboardTypeDefault;
        [self.searchView.communityNameText becomeFirstResponder];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kColor_W;
    if (self.isFromLogin) { // 注册页面进入
        [self.bigNavView setTitleWithString:@"选择社区"];
        self.navDisplayType = SEGNavigationBarDisplayTypeHide;
    } else {
        self.title = self.title.length>0?self.title:@"选择社区";

        [self showCustomNavigationBackButton];
    }
    self.viewModel.showType = SEGTableViewShowType_SelectList;
    
    //    //默认 深圳市
    //    self.viewModel.cityCode = @"340";
    //    self.viewModel.cityName = @"深圳市";
    //    self.viewModel.locatedCityName = self.viewModel.cityName;
    
    [self seg_showCity];
    // 定位、获取同城热门社区
    [self seg_locate];
    [self.view addSubview:self.tableView];
    if (!self.isFromLogin) {
        //获取搜索记录
        [self seg_requestHistoryCommunityList];
    }
}

#pragma mark - Load Data
- (void)seg_showCity {
    //显示
    if (self.viewModel.cityName && self.viewModel.cityName.length > 0) {
        [self.searchView setCityName:self.viewModel.cityName];
    } else {
        [self.searchView setCityName:@"选择城市"];
    }
    if (!self.selectCityView.hidden) {
        // 显示当前定位城市
        self.selectCityView.currentCityName = self.viewModel.locatedCityName;
    }
    [self seg_requestHotCommunityList];
}
// 获取我的搜索历史
- (void)seg_requestHistoryCommunityList {
    @weakify(self);
    [self.viewModel.searchHistorySignal subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [self.tableView reloadData];
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
    }];
}
- (void)seg_locate {
    [[CCLocationManager shareLocation] getUserLocationInfo];
    WeakSelf;
    [self.locationManager requestLocationWithReGeocode:YES withNetworkState:NO completionBlock:^(BMKLocation * _Nullable location, BMKLocationNetworkState state, NSError * _Nullable error) {
        if (error)
        {
        }
        if (location.rgcData) {
        }
        
        if (@available(iOS 8.0, *)) {
            CLAuthorizationStatus authStatus = [CLLocationManager authorizationStatus];
            BOOL isLocationServicesEnabled = [CLLocationManager locationServicesEnabled];//
            BOOL isAuth = (authStatus == kCLAuthorizationStatusAuthorizedWhenInUse || authStatus == kCLAuthorizationStatusAuthorizedAlways);
            if (isLocationServicesEnabled && isAuth)
            {
                //只有定位到才赋值，否则保存默认
                BMKLocationReGeocode *rgcData = location.rgcData;//[[BMKLocationReGeocode alloc] init];
                if (rgcData.cityCode && rgcData.cityCode.length > 0) {
                    //有变化 重新请求展示
                    if(![rgcData.cityCode isEqualToString:weakSelf.viewModel.cityCode]) {
                        weakSelf.viewModel.cityCode = rgcData.cityCode;
                        weakSelf.viewModel.cityName = rgcData.city;
                        weakSelf.viewModel.locatedCityName = weakSelf.viewModel.cityName;
                        
                        [weakSelf seg_showCity];
                    }
                } else {
                    [SEGAlertView showTmepMessageWithMessage:@"定位失败，请检查手机系统设置"];
                }
            }
            else if (authStatus == kCLAuthorizationStatusDenied){
                
                NSString *message = [NSString stringWithFormat:@"请到手机系统的【设置】>【隐私】>【定位服务】中打开定位服务，并允许%@使用定位服务", kAppName];
                
                weakSelf.alertView = [[UIAlertView alloc] initWithTitle:@"无法获取您的位置信息" message:message delegate:nil cancelButtonTitle:@"我知道了" otherButtonTitles:nil, nil];
                [weakSelf.alertView show];
                
            }
        } else {
            // Fallback on earlier versions
        }
        
    }];
}
// 判断传入的小区id来请求 选择小区接口
- (void)seg_requestUserAppRegisterOrPassWithCommunityId:(NSString *)communityId
                                          communityName:(NSString *)communityName {
    RACTuple *tuple = RACTuplePack(communityId, communityName, self.tel, self.code, self.pwd, self.randomToken);
    [self.viewModel.registerCommand.executing subscribeNext:^(NSNumber * _Nullable x) {
        if (x.boolValue) {
            [SVProgressHUD show];
        } else {
            [SVProgressHUD dismiss];
        }
    }];
    [[self.viewModel.registerCommand execute:tuple] subscribeNext:^(id  _Nullable x) {
        // 登录成功后保存注册标识，后续请求注册积分行为
        [[SEGUhomeMediator sharedInstance] seg_pushToMainViewControllerThroughInterface:@{@"isNewUserRegister":@(YES)}];
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
    }];
}
// 获取同城热门社区
- (void)seg_requestHotCommunityList {
    @weakify(self);
    self.tagList = nil;
    [self.viewModel.hotCommunitySignal subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        self.tagList.hidden = NO;
        [self.tagList deleteAllTag];
        [self.tagList addTags:self.viewModel.tagsArray];
        [self.tableView reloadData];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self.tableView reloadData];
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
    }];
}
// 获取城市列表
- (void)seg_requestCityList {
    @weakify(self);
    [self.viewModel.cityListSignal subscribeNext:^(NSArray<SEGCityListModel *> *cityList) {
        @strongify(self);
        self.selectCityView.cityListModelArray = cityList;
    }];
}
// 切换小区
- (void)seg_requestChangeCommunity {
    [self.viewModel.changeCommunitySignal subscribeNext:^(id  _Nullable x) {
        [SVProgressHUD dismiss];
        // 请求极光推送TAG接口，绑定TAG
        [[SEGUhomeMediator sharedInstance] seg_requestGetPushTag:nil];
        [[SEGUhomeMediator sharedInstance] seg_pushToMainViewControllerThroughInterfaceV2:nil];
    } error:^(NSError * _Nullable error) {
        [SVProgressHUD dismiss];
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
    }];
}
// 搜索小区
- (void)seg_requestFindCommunityByName:(NSString *)communityName {
    @weakify(self);
    [[self.viewModel.searchCommunityCommand execute:communityName] subscribeNext:^(NSNumber *dataCount) {
        @strongify(self);
        if (dataCount.integerValue == 0) {
            // 没有搜索到相关小区
            self.noSearchResultView.hidden = NO;
        } else {
            self.noSearchResultView.hidden = YES;
            // 显示搜索列表
            self.viewModel.showType = SEGTableViewShowType_SearchList;
            [self.tableView reloadData];
        }
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
    }];
}

#pragma mark - Event
// 导航栏跳过的逻辑，传小区id为1  显示虚拟小区
- (void)onNavigationRightButtonClicked:(UIButton *)sender {
    NSMutableArray *array = [self.navigationController.viewControllers mutableCopy];
    [array removeAllObjects];
    [self.navigationController setViewControllers:array animated:YES];
    
    //注册到当前小区
    [self seg_requestUserAppRegisterOrPassWithCommunityId:@"1" communityName:@"童话镇"];
}
// 左侧按钮
- (void)onNavigationLeftButtonClicked:(UIButton *)sender {
    if (self.viewModel.showType == SEGTableViewShowType_SearchList) {//正在展示搜索列表
        [self.view endEditing:YES];
        self.searchView.communityNameText.text = nil;
        // 收起搜索列表
        self.viewModel.showType = SEGTableViewShowType_SelectList;
        [self.tableView reloadData];
        return;
    }
    
    // 需要先判断noserch页面是否存在
    if (_noSearchResultView && !self.noSearchResultView.hidden) {//正在展示搜索无结果界面
        [self.view endEditing:YES];
        self.searchView.communityNameText.text = nil;
        // 收起搜索无结果界面
        self.noSearchResultView.hidden = YES;
        return;
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}
// 点击小区按钮
- (void)seg_cityButtonCliked {
    [self.view endEditing:YES];
    if (self.selectCityView.hidden) {
        self.noSearchResultView.hidden = YES;
        [self.searchView.communityNameText resignFirstResponder];
        self.searchView.cityButton.selected = YES;
        [self.view bringSubviewToFront:self.selectCityView];
        self.selectCityView.hidden = NO;
        self.selectCityView.currentCityName = self.viewModel.locatedCityName; // 显示当前定位城市
        [self seg_requestCityList];
    } else { // 收起城市列表
        self.searchView.cityButton.selected = NO;
        self.selectCityView.hidden = YES;
    }
}
- (void)seg_noSearchResultConfirm {
    [self.view endEditing:YES];
    self.noSearchResultView.hidden = YES;
    NSString *content = [NSString stringWithFormat:@"搜索不到：%@",self.searchView.communityNameText.text];
    RACTuple *tuple = RACTuplePack([NSNumber numberWithBool:self.isFromLogin], content);
    @weakify(self);
    [[self.viewModel.noSearchResultCommand execute:tuple] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        if (self.isFromLogin) {
            // 入口：注册新用户 选择小区
            [self seg_requestUserAppRegisterOrPassWithCommunityId:self.viewModel.communityId communityName:self.viewModel.communityName];
        } else {
            // 切换小区
            [self seg_saveAndChangeCommunity];
        }
    }];
}
// 保存并切换小区
- (void)seg_saveAndChangeCommunity {
    [SVProgressHUD showWithStatus:[NSString stringWithFormat:@"正在为您切换“%@”",self.viewModel.communityName]];
    if ([self seg_checkHasContentCurrentCommunity]) {
        // 切换小区
        [self seg_requestChangeCommunity];
    } else {
        // 添加到历史记录
        @weakify(self);
        [self.viewModel.saveHistorySignal subscribeNext:^(id  _Nullable x) {
            @strongify(self);
            // 切换小区
            [self seg_requestChangeCommunity];
        } error:^(NSError * _Nullable error) {
            [SVProgressHUD dismiss];
            [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
        }];
    }
}
// 判断时候添加过当前选中小区
- (BOOL)seg_checkHasContentCurrentCommunity {
    // 当前小区在历史记录中已被过滤，需要单独判断
    if([self.viewModel.communityId isEqualToString:kAccountCommunityID]) return YES;
    // 先判断是否包含要添加的小区
    __block BOOL hasAdd = NO;
    // 判断时候添加过当前选中小区
    [self.viewModel.historyArray enumerateObjectsUsingBlock:^(SEGChangeCommunityModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.communityId isEqualToString:self.viewModel.communityId]) {
            hasAdd = YES;
            *stop = YES;
        }
    }];
    return hasAdd;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    switch (self.viewModel.showType) {
        case SEGTableViewShowType_SelectList:
            return 3;
        case SEGTableViewShowType_SearchList:
            return 1;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    switch (self.viewModel.showType) {
        case SEGTableViewShowType_SelectList:
        {
            SEGSelectCommunitySectionType sectionType = section;
            switch (sectionType) {
                case SEGSelectCommunitySectionType_CurrentCommunity:
                    if (self.isFromLogin) {
                        return 0;
                    }
                    return 1;
                case SEGSelectCommunitySectionType_SearchHistory:
                {
                    if (self.viewModel.historyArray.count > 2) {
                        return self.viewModel.isShowAllHistoryList ? self.viewModel.historyArray.count + 1 : 3;
                    }else {
                        return self.viewModel.historyArray.count;
                    }
                }
                case SEGSelectCommunitySectionType_HotCommunity:
                    return 0;
            }
        }
        case SEGTableViewShowType_SearchList:
            return self.viewModel.searchCommunityArray.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SEGNewSelectCommunityCell* cell = [tableView dequeueReusableCellWithIdentifier:KSEGNewSelectCommunityCellIdentifier forIndexPath:indexPath];
    switch (self.viewModel.showType) {
        case SEGTableViewShowType_SelectList:
        {
            SEGSelectCommunitySectionType sectionType = indexPath.section;
            switch (sectionType) {
                case SEGSelectCommunitySectionType_CurrentCommunity:
                {
                    [cell showCellWithType:SEGNewSelectCommunityCellType_Community cityName:nil communityName:kAccountCommunityName indexPath:indexPath];
                    break;
                }
                case SEGSelectCommunitySectionType_SearchHistory:
                {
                    NSInteger count = [tableView numberOfRowsInSection:indexPath.section];
                    if (self.viewModel.historyArray.count > 2 && indexPath.row == count - 1) {//最后一行显示展开或收起
                        cell.isShowAll = self.viewModel.isShowAllHistoryList;
                        [cell showCellWithType:SEGNewSelectCommunityCellType_ShowAll cityName:nil communityName:nil indexPath:indexPath];
                    }else {
                        if(self.viewModel.historyArray.count > indexPath.row) {
                            SEGChangeCommunityModel *model = self.viewModel.historyArray[indexPath.row];
                            [cell showCellWithType:SEGNewSelectCommunityCellType_History cityName:model.cityName communityName:model.communityName indexPath:indexPath];
                        }
                    }
                    cell.delegate = self;
                    break;
                }
                case SEGSelectCommunitySectionType_HotCommunity:
                {
                    break;
                }
            }
            break;
        }
        case SEGTableViewShowType_SearchList: {
            if (indexPath.row < self.viewModel.searchCommunityArray.count) {
                SEGSearchCommunityModel *model = self.viewModel.searchCommunityArray[indexPath.row];
                [cell showCellWithType:SEGNewSelectCommunityCellType_Search cityName:model.cityName communityName:model.communityName indexPath:indexPath];
            }
            break;
        }
    }
    
    return cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    switch (self.viewModel.showType) {
        case SEGTableViewShowType_SelectList:
        {
            SEGSelectCommunitySectionType sectionType = section;
            switch (sectionType) {
                case SEGSelectCommunitySectionType_CurrentCommunity:
                    return self.isFromLogin ? 0: KSelectCommunityHeaderHeight;
                case SEGSelectCommunitySectionType_SearchHistory:
                    return self.viewModel.historyArray.count > 0 ? KSelectCommunityHeaderHeight : 0.01;
                case SEGSelectCommunitySectionType_HotCommunity:
                    return self.viewModel.hotCommunityArray.count > 0 ? KSelectCommunityHeaderHeight : 0.01;
            }
        }
        case SEGTableViewShowType_SearchList:
        {
            if (self.viewModel.cityCode && self.viewModel.cityCode.length > 0) {
                return 0.01;
            }else {
                return 44.0;
            }
        }
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    switch (self.viewModel.showType) {
        case SEGTableViewShowType_SelectList:
        {
            if (section == SEGSelectCommunitySectionType_HotCommunity) {
                return CGRectGetHeight(self.tagList.frame) + 5;
            }else {
                return 0.01;
            }
        }
        case SEGTableViewShowType_SearchList:
        {
            return 0.01;
        }
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (self.viewModel.showType) {
        case SEGTableViewShowType_SelectList:
        {
            // 点击到最后收起一行，不做处理
            if (indexPath.row >= self.viewModel.historyArray.count) {
                return;
            }
            if (indexPath.section == SEGSelectCommunitySectionType_SearchHistory) {
                SEGChangeCommunityModel *model = self.viewModel.historyArray[indexPath.row];
                self.viewModel.communityId = model.communityId;
                self.viewModel.communityName = model.communityName;
                //切换小区
                [self seg_saveAndChangeCommunity];
            }
            break;
        }
        case SEGTableViewShowType_SearchList:
        {
            [self.view endEditing:YES];
            
            SEGSearchCommunityModel *model = self.viewModel.searchCommunityArray[indexPath.row];
            self.viewModel.communityId = model.communityId;
            self.viewModel.communityName = model.communityName;
            if (self.isFromLogin) {
                // 入口：注册新用户 选择小区
                [self seg_requestUserAppRegisterOrPassWithCommunityId:model.communityId communityName:model.communityName];
            }else {
                //切换小区
                [self seg_saveAndChangeCommunity];
            }
            break;
        }
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (self.viewModel.showType == SEGTableViewShowType_SelectList) {
        SEGSelectCommunityHeaderView *headerView = [[SEGSelectCommunityHeaderView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.tableView.frame), KSelectCommunityHeaderHeight)];
        headerView.type = SEGCommunityHeaderType_Bottom;
        SEGSelectCommunitySectionType sectionType = section;
        switch (sectionType) {
            case SEGSelectCommunitySectionType_CurrentCommunity:
            {
                UIImage *image = self.isFromLogin ? nil : [UIImage imageWithContentsOfFile:SEGPicName(@"icon_xzsq_location")];
                headerView.iconImg.image = image;
                headerView.text = self.isFromLogin ? @"" : @"当前社区";
                break;
            }
            case SEGSelectCommunitySectionType_SearchHistory:
            {
                UIImage *image = self.viewModel.historyArray.count > 0 ? [UIImage imageWithContentsOfFile:SEGPicName(@"icon_xzsq_records")] : nil;
                headerView.iconImg.image = image;
                headerView.text = self.viewModel.historyArray.count > 0 ? @"历史记录" : @"";
                break;
            }
            case SEGSelectCommunitySectionType_HotCommunity:
            {
                UIImage *image = self.viewModel.hotCommunityArray.count > 0 ? [UIImage imageWithContentsOfFile:SEGPicName(@"icon_xzsq_samecity")] : nil;
                headerView.iconImg.image = image;
                headerView.text = self.viewModel.hotCommunityArray.count > 0 ? @"同城热门社区" : @"";
                break;
            }
        }
        return headerView;
    }else if (self.viewModel.showType == SEGTableViewShowType_SearchList) {
        if (self.viewModel.cityCode && self.viewModel.cityCode.length > 0) {
            return [UIView new];
        }else {
            UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.tableView.frame), 44.0)];
            headerView.backgroundColor = kColor_W;
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, CGRectGetWidth(self.tableView.frame), 44.0)];
            label.textColor = kColor_1;
            label.font = kFont_16;
            label.text = @"您尚未选择城市，已为您查询全部搜索结果";
            label.textAlignment = NSTextAlignmentLeft;
            [headerView addSubview:label];
            UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 43.5, CGRectGetWidth(self.tableView.frame), 0.5)];
            line.backgroundColor = kColor_L2;
            [headerView addSubview:line];
            return headerView;
        }
    }else {
        return [UIView new];
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (section == SEGSelectCommunitySectionType_HotCommunity) {
        UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), CGRectGetHeight(self.tagList.frame)+5)];
        footerView.backgroundColor = kColor_W;
        [footerView addSubview:self.tagList];
        return footerView;
    }else {
        return [UIView new];
    }
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (!self.selectCityView.hidden) {
        // 选择城市时不能搜索小区
        [SEGAlertView showTmepMessageWithMessage:@"请选择城市"];
        return NO;
    }else {
        return YES;
    }
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([string isEqualToString:@"\n"]) { // 判断输入的字是否是回车，即按下return
        [self.searchView.communityNameText resignFirstResponder];
        // 在这里做你响应return键的代码
        // 删除前后空格
        NSString *str = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        if (!str || str.length == 0) {
            [SEGAlertView showTmepMessageWithMessage:@"请输入社区名称"];
        } else {
            [self.view endEditing:YES];
            [self seg_requestFindCommunityByName:str];
        }
    }
    
    return YES;
}
- (void)seg_textFieldEditChanged:(UITextField *)textField {
    // 删除前后空格
    NSString *str = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSInteger length = str.length;
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0]; // 高亮
    if (!position) { // 没高亮的文字
        if (length >= 2) {
            [self seg_requestFindCommunityByName:str];
        }
    }
}

#pragma mark - SEGNewSelectCommunityCellDelegate
- (void)deleteButtonClickedWithIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row >= self.viewModel.historyArray.count) return;
    SEGChangeCommunityModel *model = self.viewModel.historyArray[indexPath.row];
    @weakify(self);
    [[self.viewModel.deleteCommunityCommand execute:model.communityId] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [self seg_requestHistoryCommunityList];
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
    }];
}
- (void)showAllButtonClicked {
    self.viewModel.isShowAllHistoryList = !self.viewModel.isShowAllHistoryList;
    [self.tableView reloadData];
}

#pragma mark - SEGSelectCityViewDelegate (切换城市)
- (void)selectedCityWithCode:(NSString *)cityCode cityName:(NSString *)cityName {
    self.viewModel.cityCode = cityCode;
    self.viewModel.cityName = cityName;
    self.searchView.cityButton.selected = NO;
    [self seg_showCity];
    
    // 切换城市
    NSString *searchStr = [self.searchView.communityNameText.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (searchStr.length > 0) {
        [self seg_requestFindCommunityByName:searchStr];
    } else {
        self.noSearchResultView.hidden = YES;
        [self.view endEditing:YES];
        // 收起搜索列表
        self.viewModel.showType = SEGTableViewShowType_SelectList;
        [self.tableView reloadData];
    }
}
- (void)relocateAction {
    [self seg_locate];
}

#pragma mark - Getter
- (SEGBigNavigationView *)bigNavView {
    if (!_bigNavView) {
        _bigNavView = [[SEGBigNavigationView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), KBigNavHeight)];
        [self.view addSubview:_bigNavView];
    }
    return _bigNavView;
}
- (UITableView *)tableView {
    if (!_tableView) {
        CGFloat nav_height = kNavigationBarAndStatusBarHeight;
        if (self.isFromLogin) nav_height = KBigNavHeight;
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.searchView.bottom, LYScreenWidth(), LYScreenHeight()-self.searchView.height-nav_height) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.sectionFooterHeight = 0;
        _tableView.backgroundColor = kColor_W;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsHorizontalScrollIndicator = NO;
        [_tableView registerClass:[SEGNewSelectCommunityCell class] forCellReuseIdentifier:KSEGNewSelectCommunityCellIdentifier];
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.estimatedSectionHeaderHeight  = _tableView.estimatedSectionHeaderHeight > 0 ? _tableView.estimatedSectionHeaderHeight : 0;
            _tableView.estimatedSectionFooterHeight  = _tableView.estimatedSectionFooterHeight > 0 ? _tableView.estimatedSectionFooterHeight : 0;
        }
    }
    return _tableView;
}

- (SEGCommunitySearchView *)searchView {
    if (!_searchView) {
        CGFloat origin_y = 0;
        if (self.isFromLogin) origin_y = KBigNavHeight+5;
        CGRect rect = CGRectMake(0, origin_y, CGRectGetWidth(self.view.frame), kCommunitySearchViewHeight);
        _searchView = [[SEGCommunitySearchView alloc] initWithFrame:rect];
        [_searchView.cityButton addTarget:self action:@selector(seg_cityButtonCliked) forControlEvents:UIControlEventTouchUpInside];
        _searchView.communityNameText.delegate = self;
        [_searchView.communityNameText addTarget:self action:@selector(seg_textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
        [self.view addSubview:_searchView];
    }
    return _searchView;
}
- (SEGNoSearchCommunityResultView *)noSearchResultView {
    if (!_noSearchResultView) {
        CGFloat nav_height = kNavigationBarAndStatusBarHeight;
        if (self.isFromLogin) nav_height = KBigNavHeight+5;
        _noSearchResultView = [[SEGNoSearchCommunityResultView alloc] initWithFrame:CGRectMake(0, self.searchView.bottom, LYScreenWidth(), LYScreenHeight()-self.searchView.height-nav_height)];
        if (_noSearchResultView.confirmButton) {
            [_noSearchResultView.confirmButton addTarget:self
                                                  action:@selector(seg_noSearchResultConfirm)
                                        forControlEvents:UIControlEventTouchUpInside];
        }
        [self.view addSubview:_noSearchResultView];
    }
    return _noSearchResultView;
}
- (SEGSelectCityView *)selectCityView {
    if (!_selectCityView) {
        CGFloat nav_height = kNavigationBarAndStatusBarHeight;
        if (self.isFromLogin) nav_height = KBigNavHeight+5;
        _selectCityView = [[SEGSelectCityView alloc] initWithFrame:CGRectMake(0, self.searchView.bottom, LYScreenWidth(), LYScreenHeight()-self.searchView.height-nav_height)];
        [self.view addSubview:_selectCityView];
        _selectCityView.delegate = self;
        _selectCityView.hidden = YES;
    }
    return _selectCityView;
}
- (SEGTagList *)tagList {
    if (!_tagList) {
        _tagList = [[SEGTagList alloc] init];
        _tagList.backgroundColor = kColor_W;
        __weak typeof (self) weakSelf = self;
        _tagList.clickTagBlock = ^(NSString* tag) {
            [weakSelf.view endEditing:YES];
            [weakSelf.viewModel.hotCommunityArray enumerateObjectsUsingBlock:^(SEGChangeCommunityModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([obj.communityName isEqualToString:tag]) {
                    weakSelf.viewModel.communityId = obj.communityId;
                    weakSelf.viewModel.communityName = obj.communityName;
                    if (weakSelf.isFromLogin) {
                        // 入口：注册新用户 选择小区
                        [weakSelf seg_requestUserAppRegisterOrPassWithCommunityId:obj.communityId communityName:obj.communityName];
                    }else {
                        //切换小区
                        [weakSelf seg_saveAndChangeCommunity];
                    }
                    *stop = YES;
                }
            }];
            
        };
        // 高度可以设置为0，会自动跟随标题计算
        _tagList.frame = CGRectMake(20, 5, LYScreenWidth() - 20 - 15, 0);
        // 设置标签背景色
        _tagList.tagBackgroundColor = kColor_L3;
        _tagList.tagMargin = tagMargin;
        _tagList.tagColor = kColor_1;
        _tagList.tagFont = kFont_13;
        _tagList.tagCornerRadius = 2;
        _tagList.tagButtonMargin = 10;//标签按钮内容间距
    }
    return _tagList;
}
- (SEGNewSelectCommunityViewModel *)viewModel {
    if (!_viewModel) _viewModel = [SEGNewSelectCommunityViewModel new];
    return _viewModel;
}
- (BMKLocationManager *)locationManager {
    if (!_locationManager) {
        _locationManager = [[BMKLocationManager alloc] init];
        _locationManager.delegate = self;
        //设置返回位置的坐标系类型
        //    _locationManager.coordinateType = BMKLocationCoordinateTypeBMK09LL;
        //设置距离过滤参数
        //    _locationManager.distanceFilter = kCLDistanceFilterNone;
        //设置预期精度参数
        //    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        //设置应用位置类型
        //    _locationManager.activityType = CLActivityTypeAutomotiveNavigation;
        //设置是否自动停止位置更新
        //    _locationManager.pausesLocationUpdatesAutomatically = NO;
        //设置是否允许后台定位
        //    _locationManager.allowsBackgroundLocationUpdates = YES;
        //设置位置获取超时时间
        _locationManager.locationTimeout = 10;
        //设置获取地址信息超时时间
        _locationManager.reGeocodeTimeout = 10;
    }
    return _locationManager;
}

#pragma mark - BMKLocationManagerDelegate
/**
 *  @brief 当定位发生错误时，会调用代理的此方法。
 *  @param manager 定位 BMKLocationManager 类。
 *  @param error 返回的错误，参考 CLError 。
 */
- (void)BMKLocationManager:(BMKLocationManager * _Nonnull)manager didFailWithError:(NSError * _Nullable)error
{
    
}

/**
 *  @brief 定位权限状态改变时回调函数
 *  @param manager 定位 BMKLocationManager 类。
 *  @param status 定位权限状态。
 */
- (void)BMKLocationManager:(BMKLocationManager * _Nonnull)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    if (@available(iOS 8.0, *)) {
        if(([CLLocationManager locationServicesEnabled] && status == kCLAuthorizationStatusNotDetermined)
           || status == kCLAuthorizationStatusAuthorizedWhenInUse) {
            //如果通过系统设置打开授权后，收起自己的弹窗
            if(self.alertView && self.alertView.hidden == NO) {
                [self.alertView dismissWithClickedButtonIndex:0 animated:NO];
            }
        }
    } else {
        // Fallback on earlier versions
    }
    
    // 类方法，判断是否开启定位服务
    if ([CLLocationManager locationServicesEnabled]) {
    } else {
    }
    
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
        {
            break;
        }
        case kCLAuthorizationStatusRestricted:
        {
            break;
        }
        case kCLAuthorizationStatusDenied:
        {
            // 类方法，判断是否开启定位服务
            if ([CLLocationManager locationServicesEnabled]) {
            } else {
            }
            break;
        }
        case kCLAuthorizationStatusAuthorizedAlways:
        {
            break;
        }
        case kCLAuthorizationStatusAuthorizedWhenInUse:
        {
            break;
        }
        default:
            break;
    }
}

/**
 * @brief 该方法为BMKLocationManager所在App系统网络状态改变的回调事件。
 * @param manager 提供该定位结果的BMKLocationManager类的实例
 * @param state 当前网络状态
 * @param error 错误信息
 */
- (void)BMKLocationManager:(BMKLocationManager * _Nonnull)manager
     didUpdateNetworkState:(BMKLocationNetworkState)state orError:(NSError * _Nullable)error
{
    
}


@end
